/**
 * 
 */
package com.interactiveyang.meet;

import java.util.ArrayList;
import java.util.Collections;

import com.google.gson.Gson;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

/**
 * @author yangliu
 *
 */
public class SelfManagementPage extends Activity implements OnClickListener {
	
	EditText input;
	Button shoutButton;
	ListView shoutHistory;
	
	Bundle extras;
	
//	String shoutHistoryFromSQL[] = {"this is 1", "this is 1","this is 1","this is 1","this is 1","this is 1","this is 1","this is 1","this is 1"};
	ArrayList<String> shoutHistoryFromSQL = new ArrayList<String>();
	
	@Override
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		C.setFullScreen(this);
        setContentView(R.layout.selfmanagementpage);
        
        input = (EditText) findViewById(R.id.ShoutInput);
        shoutButton = (Button) findViewById(R.id.ShoutButton);
        shoutHistory = (ListView) findViewById(R.id.ShoutHistory);
        
		extras = getIntent().getExtras();
        
        if(extras.containsKey("username")){
        	C.alert(this, extras.getString("username"));
        	
        	getSelfShout();
        }
//        shoutHistory.addFooterView(shoutButton);
        shoutHistory.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, shoutHistoryFromSQL));
        
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        input.setOnClickListener(this);
        shoutButton.setOnClickListener(this);
	}
	
	public void getSelfShout(){
		String userShout = C.MeetBack.backendRequest.getUserShout(extras.getString("username"));
    	Gson gson = new Gson();
    	
//    	C.alert(this, userShout);
    	
    	UserShout shoutContent = gson.fromJson("{'userShout': " + userShout + "}", UserShout.class);
    	
    	if(userShout != null){
    		for(int i=0; i< shoutContent.userShout.length; i++){
        		shoutHistoryFromSQL.add(shoutContent.userShout[i].shoutcontent);
        	}
    		Collections.reverse(shoutHistoryFromSQL);
    	}
	}
	
	@Override
	public void onClick(View v) {
		if(v == input){
			((EditText)v).setText("");
		}
		else if(v == shoutButton){
			String shoutContent = input.getText().toString();
			String username = MapPage.USERNAME;
			
			if(C.MeetBack.backendRequest.publishShoot(shoutContent, username)){
				C.alert(this, "shout successed!!!");
//				getSelfShout();
				(input).setText("");
			}
			else{
				C.alert(this, "shout failed!!!");
			}
		}
	}
}
